﻿using Bll;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Web.Models;

namespace Web.Controllers
{
    public class CustomerController : Controller
    {
        public ActionResult List()
        {
            BaseModel model = new BaseModel();
            return View(model);
        }

        [HttpPost]
        public string GetCustomer(string strWhere, int pageIndex)
        {
            var bll = new TableBll();
            string tblName = "Customer";
            Model_MakePages page = new Model_MakePages(tblName, strWhere, pageIndex);
            PageTable pageTable = bll.GetData_Page_FldsOrder(page);
            string str = Tool.SerializeObject(pageTable);

            return str;
        }
        [HttpPost]
        public ActionResult Delete(int id)
        {
            var bll = new CustomerBll();
            try
            {
                int result = bll.Delete(id);
                if (result > 0)
                    return JsonResultExtension.ToJsonResult(true, "操作成功");
                else
                    return JsonResultExtension.ToJsonResult(false, "操作失败");
            }
            catch (Exception e)
            {
                return JsonResultExtension.ToJsonResult(false, e.Message);
            }
        }

        public ActionResult Edit(int id = 0)
        {
            if (id == 0)
            {
                var model = new Customer();
                return View(model);
            }
            else
            {
                var model = new CustomerBll().GetById(id);
                return View(model);
            }
        }
        [HttpPost]
        public ActionResult Edit(Customer model)
        {
            var bll = new CustomerBll();
            try
            {
                ViewBag.EditResult = "<script>alert('保存失败，请稍后重试！');</script>";
                if (model.CustomerId > 0)//修改
                {
                    if (bll.Edit(model) > 0)
                    {
                        ViewBag.EditResult = "<script>alert('保存成功');document.location.href='List'</script>";
                    }
                }
                else//新增
                {
                    if (bll.Add(model) > 0)
                    {
                        ViewBag.EditResult = "<script>alert('保存成功');document.location.href='List'</script>";
                    }
                }
            }
            catch (Exception exception)
            {
                throw;
            }

            return View(model);
        }
    }
}
